package mygang.singleton;

import java.util.ArrayList;
import java.util.List;
import mygang.model.BaseModel;
import mygang.model.SystemSetting;
import mygang.security.ApplicationContextProvider;
import mygang.service.SystemSettingsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

/**
 *
 * @author Volodymyr Lavrynovych <volodya.lavrynovych@gmail.com>
 * date: 10/09/2012
 */
@Component
public class Settings extends BaseModel {

    private static Settings INSTANCE = null;
    
    @Autowired
    private SystemSettingsService systemSettingsService;
    private static List<SystemSetting> settings = new ArrayList<SystemSetting>();
    
    private Settings(){
    }
    
    public static Settings getInstance(){
        if(INSTANCE==null){
            ApplicationContext context = ApplicationContextProvider.getApplicationContext();
            INSTANCE = context.getBean(Settings.class);
        }
        return INSTANCE;
    }
    
    public SystemSetting getSystemSettingById(long id) {
        for(SystemSetting setting : getSettings()){
            if(setting.getId()==id) return setting;
        }
        return null;
    }

    public SystemSetting getSystemSettingByName(String name) {
        for(SystemSetting setting : getSettings()){
            if(setting.getName().equals(name)) return setting;
        }
        return null;
    }
    
    public void refresh(){
        settings = systemSettingsService.getAll();
    }
    
    protected List<SystemSetting> getSettings(){
        if(settings==null || settings.isEmpty()) refresh();
        return settings;
    }
}